package com.itheima.test11;

/**
 * @Author:gy
 * @Date: 2025/09/01 16:05
 * @Description:
 */
public class MyRunable implements Runnable{
    private static int ticketCount = 100;
    private static Object obj = new Object();
    @Override
    public void run() {
        //窗口一  同步方法去买票   窗口二用同步代码块去卖票
        while(true){
            //如果是窗口一
            if("窗口一".equals(Thread.currentThread().getName())){
                //同步方法
                boolean b = sellTicket();
                if(b){
                    break;
                }
            }
            if("窗口二".equals(Thread.currentThread().getName())){
                //同步代码块
                synchronized (MyRunable.class) {//这里面需要加一个锁
                    if(ticketCount <= 0){
                        //不能卖了
                        break;
                    }else{
                        //可以卖票
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName()+"正在卖票,还剩下"+ticketCount+"张票");
                    }
                }
            }
        }
    }

    //锁对象是this
    public static synchronized boolean sellTicket(){
        if(ticketCount <= 0){
            //不能卖了
            return true;
        }else{
            //可以卖票
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName()+"正在卖票,还剩下"+ticketCount+"张票");
            return false;
        }
    }
}
